package com.rio.helper.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.text.GetChars;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rio.core.L;
import com.rio.core.U;

public class G {
	
	private static Gson mGson;
	
	public static Gson getGson(){
		if(U.isNull(mGson))
			mGson = new Gson();
		return mGson;
	}

	
	public static String toJson(Object target){
		if(U.isNull(target))
			return null;
		return getGson().toJson(target);
		
	}
	
	public static <T> T toObject(String json,Class<T> cls){
		if(U.isNull(json))
			return null;
		try {
			return getGson().fromJson(json, cls);
		} catch (Exception e) {
			L.e(e);
			return null;
		}			
	}
	
	public static <T> ArrayList<T> toList(String json,Class<T> cls){
		if(U.isNull(json))
			return null;
		try {
			ArrayList<T> list = new ArrayList<T>();
			JSONArray jsonArray = new JSONArray(json);
			JSONObject objItem = null;
			T objT = null;
			for (int i = 0; i < jsonArray.length(); i++) {
				objItem = (JSONObject) jsonArray.get(i);
				if(U.notNull(objItem)){
					objT = getGson().fromJson(objItem.toString(), cls);
					list.add(objT);
				}
		    }	
			return list;
		} catch (Exception e) {
			return null;
		}			
	}
	
	public static <T> ArrayList<T> toList(JSONArray jsonArray,Class<T> cls){
		if(U.isNull(jsonArray))
			return null;
		try {
			ArrayList<T> list = new ArrayList<T>();
			JSONObject objItem = null;
			T objT = null;
			for (int i = 0; i < jsonArray.length(); i++) {
				objItem = (JSONObject) jsonArray.get(i);
				if(U.notNull(objItem)){
					objT = getGson().fromJson(objItem.toString(), cls);
					list.add(objT);
				}
		    }	
			return list;
		} catch (Exception e) {
			return null;
		}			
	}
	
	
}
